package main

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

func maxIncreaseKeepingSkyline(grid [][]int) int {
	m := len(grid)
	n := len(grid[0])
	rawMax := make([]int, m)
	columnMax := make([]int, n)
	for i, row := range grid {
		for j, height := range row {
			if height > rawMax[i] {
				rawMax[i] = height
			}
			if height > columnMax[j] {
				columnMax[j] = height
			}
		}
	}
	result := 0
	for i, row := range grid {
		for j, h := range row {
			maxH := min(rawMax[i], columnMax[j])
			result += maxH - h
		}
	}
	return result
}